<script setup lang="ts">
import { getGoodsByIdAPI } from '@/services/detailGoods';
import type { GoodsResult } from '@/types/goods';
import { onLoad } from '@dcloudio/uni-app';
import { computed, ref } from 'vue';
import servicePanel from './components/servicePanel.vue';
import addressPanel from './components/addressPanel.vue';
import pageSkeleton from './components/pageSkeleton.vue';
import type {
  SkuPopupEvent,
  SkuPopupInstance,
  SkuPopupLocaldata,
} from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup';
import { postMemberCartAPI } from '@/services/cart';
import type { AddressItem } from '@/types/address';
import { useAddressStore } from '@/stores/modules/address';

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();

// 接收页面参数
const query = defineProps<{
  id: string;
}>();
//获取商品详情数据
const goods = ref<GoodsResult>();
const getGoodsByIdData = async () => {
  const res = await getGoodsByIdAPI(query.id);
  goods.value = res.result;
  //准备SKU组件格式数据
  localdata.value = {
    _id: res.result.id,
    name: res.result.name,
    goods_thumb: res.result.mainPictures[0],
    spec_list: res.result.specs.map((v) => {
      return {
        name: v.name,
        list: v.values,
      };
    }),
    sku_list: res.result.skus.map((sku) => {
      return {
        _id: sku.id,
        goods_id: res.result.id,
        goods_name: res.result.name,
        image: sku.picture,
        price: sku.price * 100, //注意：价格要*100
        stock: sku.inventory,
        sku_name_arr: sku.specs.map((v) => v.valueName),
      };
    }),
  };
};
// 是否加载完成
const isfinish = ref(false);
// 页面加载
onLoad(async () => {
  await getGoodsByIdData();
  isfinish.value = true;
});

// 轮播图变化时
const currentIndex = ref(0);
const onChange: UniHelper.SwiperOnChange = (event) => {
  currentIndex.value = event.detail.current;
};

// 点击轮播图图片预览
const onTapImage = (url: string) => {
  uni.previewImage({
    current: url,
    urls: goods.value!.mainPictures,
  });
};
//  uni-ui 弹出层组件 ref
const popup = ref<{
  open: (type?: UniHelper.UniPopupType) => void;
  close: () => void;
}>();

// 弹出层条件渲染
const popupName = ref<'address' | 'service'>();
const openPopup = (name: typeof popupName.value) => {
  // 修改弹出层名称
  popupName.value = name;
  // 打开弹出层
  popup.value?.open();
};
// 是否显示SKU弹出层
const isShowSku = ref(false);
// SKU商品信息本地数据源
const localdata = ref({} as SkuPopupLocaldata);
// 弹出层按钮模式
enum SkuMode {
  Both = 1,
  cart = 2,
  buy = 3,
}
const mode = ref<SkuMode>(SkuMode.Both);
const cartText = ref();
// 弹出层按钮模式切换
const openMode = (val: SkuMode, text?: string) => {
  // 显示弹窗
  isShowSku.value = true;
  // 修改按钮模式
  mode.value = val;
  // 修改加入购物车按钮的文字
  cartText.value = text;
};
// SKU组件实例
const SkuPopupRef = ref<SkuPopupInstance>();
// 计算被选中的值
const selectArr = computed(() => {
  return SkuPopupRef.value?.selectArr.join(' ').trim() || '请选择商品规格';
});
// 加入购物车事件
const onAddCart = async (event: SkuPopupEvent) => {
  await postMemberCartAPI({ skuId: event._id, count: event.buy_num });
  uni.showToast({ title: '添加购物车成功', icon: 'success' });
  isShowSku.value = false;
};
// 立即购买
const onBuyNow = (event: SkuPopupEvent) => {
  // 跳转页面并传参
  uni.navigateTo({
    url: `/pagesOrder/create-order/create-order?skuId=${event._id}&count=${
      event.buy_num
    }&addressId=${
      // 判断是否有选择的地址，有则使用选择的地址，否则使用默认地址
      addressStore.selectAddress
        ? addressStore.selectAddress?.id
        : goods.value?.userAddresses.find((item) => item.isDefault)?.id
    }`,
  });
  // 关闭弹出层
  isShowSku.value = false;
};
// 选择收货地址
const addressStore = useAddressStore();

const selectAddress = computed(() => {
  if (addressStore.selectAddress) {
    return `${addressStore.selectAddress?.fullLocation} ${addressStore.selectAddress?.address}`;
  } else {
    if (
      goods.value?.userAddresses !== null &&
      goods.value?.userAddresses.length! > 0 &&
      goods.value?.userAddresses.find((item) => item.isDefault === 1)
    ) {
      return (
        goods.value?.userAddresses.find((item) => item.isDefault)
          ?.fullLocation +
        ' ' +
        goods.value?.userAddresses.find((item) => item.isDefault)?.address
      );
    } else {
      return '请选择收货地址';
    }
  }
});
</script>

<template>
  <template v-if="isfinish">
    <!-- sku弹出层 -->
    <vk-data-goods-sku-popup
      v-model="isShowSku"
      :localdata="localdata"
      :mode="mode"
      :add-cart-text="cartText"
      ref="SkuPopupRef"
      @add-cart="onAddCart"
      @buy-now="onBuyNow"
    ></vk-data-goods-sku-popup>
    <scroll-view scroll-y class="viewport">
      <!-- 基本信息 -->
      <view class="goods">
        <!-- 商品主图 -->
        <view class="preview">
          <swiper circular class="swiper" @change="onChange">
            <swiper-item v-for="item in goods?.mainPictures" :key="item">
              <image @tap="onTapImage(item)" mode="aspectFill" :src="item" />
            </swiper-item>
          </swiper>
          <view class="indicator">
            <text class="current">{{ currentIndex + 1 }}</text>
            <text class="split">/</text>
            <text class="total">{{ goods?.mainPictures.length }}</text>
          </view>
        </view>

        <!-- 商品简介 -->
        <view class="meta">
          <view class="price">
            <text class="symbol">¥</text>
            <text class="number">{{ goods?.price }}</text>
            <text class="">起</text>
          </view>
          <view class="name ellipsis">{{ goods?.name }}</view>
          <view class="desc"> {{ goods?.desc }}</view>
        </view>

        <!-- 操作面板 -->
        <view class="action">
          <view class="item arrow" @tap="openMode(SkuMode.Both)">
            <text class="label">选择</text>
            <text class="text ellipsis"> {{ selectArr }} </text>
          </view>
          <view class="item arrow" @tap="openPopup('address')">
            <text class="label">送至</text>
            <text class="text ellipsis"> {{ selectAddress }}</text>
          </view>
          <view class="item arrow" @tap="openPopup('service')">
            <text class="label">服务</text>
            <text class="text ellipsis"> 无忧退 快速退款 免费包邮 </text>
          </view>
        </view>
      </view>

      <!-- 商品详情 -->
      <view class="detail panel">
        <view class="title">
          <text>详情</text>
        </view>
        <view class="content">
          <view class="properties">
            <!-- 属性详情 -->
            <view
              class="item"
              v-for="item in goods?.details.properties"
              :key="item.name"
            >
              <text class="label">{{ item.name }}</text>
              <text class="value">{{ item.value }}</text>
            </view>
          </view>
          <!-- 图片详情 -->
          <image
            v-for="item in goods?.details.pictures"
            :key="item"
            mode="widthFix"
            :src="item"
          ></image>
        </view>
      </view>

      <!-- 同类推荐 -->
      <view class="similar panel">
        <view class="title">
          <text>同类推荐</text>
        </view>
        <view class="content">
          <navigator
            v-for="item in goods?.similarProducts"
            :key="item.id"
            class="goods"
            hover-class="none"
            :url="`/pages/goods/goods?id=${item.id}`"
          >
            <image class="image" mode="aspectFill" :src="item.picture"></image>
            <view class="name ellipsis">{{ item.name }}</view>
            <view class="price">
              <text class="symbol">¥</text>
              <text class="number">{{ item.price }}</text>
            </view>
          </navigator>
        </view>
      </view>
    </scroll-view>

    <!-- 用户操作 -->
    <view
      class="toolbar"
      :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
    >
      <view class="icons">
        <button class="icons-button">
          <text class="icon-heart"></text>收藏
        </button>
        <!-- #ifdef MP-WEIXIN -->
        <button class="icons-button" open-type="contact">
          <text class="icon-handset"></text>客服
        </button>
        <!-- #endif -->
        <navigator class="icons-button" url="/pages/cart/cart2">
          <text class="icon-cart"></text>购物车
        </navigator>
      </view>
      <view class="buttons">
        <view class="addcart" @tap="openMode(SkuMode.cart, '确定')">
          加入购物车
        </view>
        <view class="buynow" @tap="openMode(SkuMode.buy)"> 立即购买 </view>
      </view>
    </view>
    <!-- uni-popup弹出层 -->
    <uni-popup ref="popup" type="bottom" background-color="#fff">
      <servicePanel
        v-if="popupName === 'service'"
        @close="popup?.close()"
      ></servicePanel>
      <addressPanel
        :address="goods?.userAddresses as AddressItem[]"
        v-if="popupName === 'address'"
        @close="popup?.close()"
      ></addressPanel>
    </uni-popup>
  </template>
  <pageSkeleton v-else></pageSkeleton>
</template>

<style lang="scss">
@import './components/styles/goods.scss';
.toolbar .icons .navigator-wrap {
  flex: 1;
}
page {
  height: 100%;
  // overflow: hidden;
  display: flex;
  flex-direction: column;
}

.viewport {
  background-color: #f4f4f4;
}

:deep(.close-item) {
  width: 35rpx !important;
  height: 35rpx !important;
  filter: drop-shadow(0 0 0 #000);
}

.panel {
  margin-top: 20rpx;
  background-color: #fff;

  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 90rpx;
    line-height: 1;
    padding: 30rpx 60rpx 30rpx 6rpx;
    position: relative;

    text {
      padding-left: 10rpx;
      font-size: 28rpx;
      color: #333;
      font-weight: 600;
      border-left: 4rpx solid #ec602b;
    }

    navigator {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.arrow {
  &::after {
    position: absolute;
    top: 50%;
    right: 30rpx;
    content: '\e6c2';
    color: #ccc;
    font-family: 'erabbit' !important;
    font-size: 32rpx;
    transform: translateY(-50%);
  }
}
</style>
